import Joi from 'joi';
import debugCheck from '@kuiper-helpers/debug-check';
import * as validation from '../../common/validation';
import findManyFilter from '../../common/validation/findManyFilter';

export const pagination = {
	tags: ['api', 'whitelist'],
	description: '白名单列表-分页查看',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			page: Joi.number().default(1).description('当前页'),
			perPage: Joi.number().default(10).description('每页条目数'),
			filter: findManyFilter.whitelist.keys({
				jobIds: Joi.string(),
				taskTypes: Joi.string(),
				createTimeGTE: Joi.date().description('开始时间。大于等于'),
				createTimeLTE: Joi.date().description('开始时间。小于等于'),
			}),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistPagination: Joi.object({
					count: Joi.number().description('总条数'),
					pageInfo: Joi.object({
						currentPage: Joi.number().description('当前页数'),
						perPage: Joi.number().description('每页条数'),
						pageCount: Joi.number().description('总页数'),
						itemCount: Joi.number().description('总条数'),
						hasNextPage: Joi.boolean().description('是否有下一页'),
						hasPreviousPage: Joi.boolean().description('是否有上一页'),
					}),
					items: Joi.array().items(
						validation.whitelistWithId.append({
							user: Joi.object({
								username: Joi.string().description('用户名'),
							}),
							job: Joi.array().items(
								Joi.object({
									_id: Joi.string(),
									target: Joi.object({
										hostname: Joi.string().description('域名'),
									}),
								})
							),
						})
					),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { page, perPage, filter },
				} = request;

				return JSON.stringify({
					variables: { page, perPage, filter },
					// #region query
					query: `
						query($page: Int = 1, $perPage: Int = 10, $filter: FilterFindManyWhitelistInput, $sort: SortFindManyWhitelistInput = _ID_DESC) {
							WhitelistPagination(page: $page, perPage: $perPage, filter: $filter, sort: $sort) {
								count
								pageInfo {
									currentPage
									perPage
									pageCount
									itemCount
									hasNextPage
									hasPreviousPage
								}
								items {
									_id
									uid
									jobIds
									validStartTime
									validEndTime
									urls
									taskTypes
									vulWarnIds
									normalEventWarnIds
									attackEventWarnIds
									explicitKeywords
									note
									enable
									createTime
									modifiedBy
									updateTime
									job {
										_id
										target {
											hostname
										}
									}
									user {
										username
									}
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const findById = {
	tags: ['api', 'whitelist'],
	description: '根据ID查询监测白名单',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		params: Joi.object({
			whitelistId: Joi.string(),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistById: validation.whitelistWithId,
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					params: { whitelistId },
				} = request;

				return JSON.stringify({
					variables: { _id: whitelistId },
					// #region query
					query: `
						query($_id: MongoID!) {
							WhitelistById: WhitelistOne(filter: { _id: $_id }) {
								_id
								uid
								jobIds
								validStartTime
								validEndTime
								urls
								taskTypes
								vulWarnIds
								normalEventWarnIds
								attackEventWarnIds
								explicitKeywords
								note
								enable
								createTime
								modifiedBy
								updateTime
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const count = {
	tags: ['api', 'whitelist'],
	description: '监测白名单数量统计',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.object({
			filter: findManyFilter.whitelist.keys({
				jobIds: Joi.string(),
				taskTypes: Joi.string(),
			}),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistCount: Joi.number().description('数量'),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload: { filter },
				} = request;

				return JSON.stringify({
					variables: { filter },
					// #region query
					query: `
						query($filter: FilterCountWhitelistInput) {
							WhitelistCount(filter: $filter)
						}`,
					// #endregion
				});
			},
		},
	},
};

export const removeById = {
	tags: ['api', 'whitelist'],
	description: '删除白名单',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		params: Joi.object({
			whitelistId: Joi.string().required(),
		}),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistRemoveById: Joi.object({
					recordId: Joi.string(),
				}).allow(null),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					params: { whitelistId },
				} = request;

				return JSON.stringify({
					variables: { whitelistId },
					// #region query
					query: `
						mutation($whitelistId: MongoID!) {
							WhitelistRemoveById: WhitelistRemoveOne(filter: { _id: $whitelistId }) {
								recordId
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const removeMany = {
	tags: ['api', 'whitelist'],
	description: '删除白名单',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: Joi.array().items(Joi.string()).required(),
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistRemoveMany: Joi.object({
					numAffected: Joi.number(),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { payload } = request;

				return JSON.stringify({
					variables: { _ids: payload },
					// #region query
					query: `
						mutation($_ids: [MongoID]!) {
							WhitelistRemoveMany(filter: { _ids: $_ids }) {
								numAffected
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

// 更新时不能添加默认值
const updateSchema = Joi.object();
validation.whitelist.$_terms.keys.forEach(({ key, schema }) => {
	if (key === 'enable') {
		updateSchema.append({ [key]: Joi.boolean() });
	} else if (key !== 'createTime') {
		updateSchema.append({ [key]: schema });
	}
});
export const updateById = {
	tags: ['api', 'whitelist'],
	description: '更新白名单',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		params: Joi.object({
			whitelistId: Joi.string().description('资产监测任务ID'),
		}),
		payload: updateSchema,
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistUpdateById: Joi.object({
					recordId: Joi.string().description('更新记录的ID'),
				}),
			}),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const {
					payload,
					params: { whitelistId },
				} = request;

				return JSON.stringify({
					variables: {
						record: payload,
						filter: {
							_id: whitelistId,
						},
					},
					// #region query
					query: `
						mutation($filter: FilterUpdateOneWhitelistInput!, $record: UpdateOneWhitelistInput!) {
							WhitelistUpdateById: WhitelistUpdateOne(filter: $filter, record: $record) {
								recordId
							}
						}`,
					// #endregion
				});
			},
		},
	},
};

export const createOne = {
	tags: ['api', 'whitelist'],
	description: '新建白名单',
	auth: debugCheck('disable-open-api-auth')
		? false
		: {
				mode: 'required',
				access: {
					// 只允许使用 URL Token 访问
					entity: 'app',
				},
		  },

	validate: {
		payload: validation.whitelist,
	},

	response: {
		schema: Joi.object({
			data: Joi.object({
				WhitelistCreateOne: Joi.object({
					recordId: Joi.string(),
					record: validation.whitelistWithId,
				}).label('WhitelistCreateOne'),
			}).label('Data'),
		}).label('Response'),
	},

	handler: {
		injectGraphql: {
			payloadBuilder(request) {
				const { payload: record } = request;

				return JSON.stringify({
					variables: {
						record,
					},
					// #region query
					query: `
						mutation($record: CreateOneWhitelistInput!) {
							WhitelistCreateOne(record: $record) {
								recordId
								record {
									_id
									uid
									jobIds
									validStartTime
									validEndTime
									urls
									taskTypes
									vulWarnIds
									normalEventWarnIds
									attackEventWarnIds
									explicitKeywords
									note
									enable
									createTime
								}
							}
						}`,
					// #endregion
				});
			},
		},
	},
};
